package cn.school.demo.ui.modify_password

import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentModifyPwdSecondBinding
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.mylhyl.circledialog.CircleDialog

class ModifyPwdSecondFragment : Fragment() {
    private lateinit var binding: FragmentModifyPwdSecondBinding
    private lateinit var viewModel: ModifyPwdViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(ModifyPwdViewModel::class.java)
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_modify_pwd_second,
            container,
            false
        )
        binding.vm = viewModel
        binding.vw = this
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    fun gotoModifyPwd() = MyApplication.goto(
        R.id.action_ModifyPwdSecond_to_ModifyPwd,
        findNavController(),
        requireFragmentManager()
    )

    fun setNewPwd() = viewModel.setNewPwd(binding.modifyPwdSecondPwdText.text.toString())
    fun setNewRePwd() = viewModel.setNewRePwd(binding.modifyPwdSecondRepwdText.text.toString())
    fun modifyPwd() {
        val toastText = viewModel.isLegal()
        toastText?.let { ToastUtils.showShort(toastText) } ?: let {
            viewModel.getResult()
            viewModel.result.observe(viewLifecycleOwner) {
                when (viewModel.result.value!!.success) {
                    true -> {
                        MyApplication.user!!.password = viewModel.newPwd.value.toString()
                        CircleDialog.Builder().setText("修改密码成功！").setNegative("确定") {
                            MyApplication.goto(
                                R.id.action_ModifyPwdSecond_to_Setting,
                                findNavController(),
                                requireFragmentManager()
                            )
                        }.show(requireFragmentManager())
                    }
                    else -> CircleDialog.Builder()
                        .setText(viewModel.result.value!!.message)
                        .setTextColor(Color.RED)
                        .setNegative("确定", null)
                        .show(requireFragmentManager())
                }
            }
        }

    }
}